#include "giza.h"

void usage()
{
	fprintf( stderr, "usage: nao2giza  nao-file  giza-file(s-t)  out-file\n" );
}

bool convert( char *nao_fn, char *giza_fn, char *out_fn )
{
	CUTextFile nao_file( nao_fn );
	if( nao_file.IsOpen() == false )	{
		fprintf( stderr, "ERROR: file open fail %s\n", nao_fn );
		return false;
	}

	CGiza giza;
	if( giza.Open( giza_fn ) == false )	{
		fprintf( stderr, "Giza file %s fail\n", giza_fn );
		return false;
	}
	fprintf( stderr, "Giza file %s opened\n", giza_fn );

	CUTextFile out_file( out_fn, "w" );
	if( out_file.IsOpen() == false )	{
		fprintf( stderr, "ERROR: file open fail %s\n", nao_fn );
		return false;
	}

	///////////
	int num_sent = 0;
	while(1)	{
		CUString line;
		if( nao_file.ReadLine( line ) == false ) break;

		if( giza.ReadSent() == false )	{
			break;
		}
		num_sent++;

		CUStringList align_list;
		align_list.TokenizeByChar( line, " ", false );


		// line1
		fprintf( out_file.GetFP(), "# Sentence pair (%d)\n", num_sent );

		// line2 tgt
		for( int i=0; i<giza.tgt.tok_list.GetSize(); i++ )	{
			if( i > 0 )	{
				fprintf( out_file.GetFP(), " " );
			}
			fprintf( out_file.GetFP(), "%s", giza.tgt.tok_list.GetAt(i) );
		}
		fprintf( out_file.GetFP(), "\n" );

		// line3 src
		for( int i=0; i<giza.src.tok_list.GetSize(); i++ )	{
			if( i != 0 )	{
				fprintf( out_file.GetFP(), " " );
			}

			fprintf( out_file.GetFP(), "%s ({", giza.src.tok_list.GetAt(i) );
			for( int j=0; j<align_list.GetSize(); j++ )	{
				CUString align = align_list.GetAt(j);
				CUStringList st;
				st.TokenizeByChar( align, "-", false );
				int sid = atoi( st.GetAt(0) );
				int tid = atoi( st.GetAt(1) );

				if( sid == i )	{
					fprintf( out_file.GetFP(), " %d", tid );
				}

			}
			fprintf( out_file.GetFP(), " })" );
		}
		fprintf( out_file.GetFP(), "\n" );

		//fprintf( out_file.GetFP(), "%s\n", line.GetStr() );

	}

	fprintf( stderr, "%d senteneces are converted\n", num_sent );



	return true;
}

int main( int argc, char *argv[] )
{
	if( argc != 4 )	{
		usage();
		return 1;
	}

	if( convert( argv[1], argv[2], argv[3] ) == false )	{
		return 1;
	}

	return 0;
}
